package com.example.wanbaqian.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.wanbaqian.R;
import com.example.wanbaqian.activity.ApplyAgainActivity;
import com.example.wanbaqian.activity.ApplyOneActivity;
import com.example.wanbaqian.activity.FindbankInfoActivity;
import com.example.wanbaqian.activity.WithdrawalsActivity;
import com.example.wanbaqian.base.BaseFragment;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.bean.ApplyOneBean;
import com.example.wanbaqian.bean.HomeWalletBean;
import com.example.wanbaqian.bean.Info;
import com.example.wanbaqian.bean.UserInfoBean;
import com.example.wanbaqian.bean.WalletFragmentMoeyBean;
import com.example.wanbaqian.bean.WithdrawalsBean;
import com.example.wanbaqian.event.ValueEvent;
import com.example.wanbaqian.utils.BaseUtils;
import com.example.wanbaqian.utils.GetJsonUtils;
import com.example.wanbaqian.utils.HttpUtils;
import com.example.wanbaqian.utils.JsonUtils;
import com.example.wanbaqian.utils.SPUtils;
import com.example.wanbaqian.widget.AutoVerticalScrollTextView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * 借款--首页
 */
public class WalletFragment extends BaseFragment implements HttpCallback {
    private static final String ARG_PARAM1 = "param1";
    private static final String TAG = "WalletFragment";
    private static final int BASETTIME = 1006;
    @BindView(R.id.mainbg)
    BGABanner mBgabanner;
    @BindView(R.id.wallet_creatBtn)
    Button walletCreatBtn;
    @BindView(R.id.redSeekBar)
    SeekBar redSeekBar;
    @BindView(R.id.yelloSeekBar)
    SeekBar yelloSeekBar;
    @BindView(R.id.lendmoey)
    TextView mLendmoney;
    @BindView(R.id.lendnums)
    TextView mLendnums;
    @BindView(R.id.rel_lendinfo)
    RelativeLayout mRel_lendinfo;

    @BindView(R.id.shouldrepay)
    TextView mShouldrepay;

    @BindView(R.id.extrapend)
    TextView mExtrarepay;

    @BindView(R.id.txt_info)
    AutoVerticalScrollTextView mInfo;


    @BindView(R.id.img_borrowhelp)
    ImageView mhelp;
    private Dialog mDialog;

    private int number = 0;
    private boolean isRunning = true;
    private HomeWalletBean bean;
    private String interest_rates;
    private UserInfoBean userInfo;

    public static WalletFragment newInstance(String param1) {
        WalletFragment fragment = new WalletFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViewsAndEvents(View view) {
        EventBus.getDefault().register(this);
        userInfo = SPUtils.getUserInfo(mContext);

        setListenter();
        setBannerdata();
        //获取综合费率
        getZHFY();

    }

    @Override
    public void onResume() {
        super.onResume();

        //2017年10月12日 首页刷新
        getUserHomeInfo();
        //获取综合费率
        getZHFY();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){

            getUserHomeInfo();
            //获取综合费率
            getZHFY();
        }
    }

    /**
     * 获取综合费用
     */
    private void getZHFY() {

        int progress = redSeekBar.getProgress();
        int mone = 500+progress*5;
        HttpUtils.getInstance().post(
                GetJsonUtils.getInstance().getRequest(HttpURL.GET_LV, mContext,
                        new String[]{"accessid", "amount"},
                        new String[]{SPUtils.getAccessid(mContext),
                                mone + ""})//这个是post第一个字段

//                        , mContext
                , null
                , CommonValue.REQUEST_CODE4
                , WalletFragment.this);
    }


    private void getUserHomeInfo() {

        Log.e(TAG, "getUserHomeInfo: "+"onResume");
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.MY_CREDIT, mContext,
                new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)}),
                mContext, "", CommonValue.REQUEST_CODE1, this);
//                mContext, HttpURL.MY_CREDIT, CommonValue.REQUEST_CODE1, this);
    }

    /**
     * 设置seekbar
     */
    private void setListenter() {

        redSeekBar.setProgress(100);
        yelloSeekBar.setMax(7);
        yelloSeekBar.setProgress(7);
        mLendmoney.setText("1000");
        mLendnums.setText("14");
        if(null != userInfo){
            interest_rates = userInfo.getInterest_rate();
        }else{
//            interest_rates = SPUtils.get()
        }
        try {
            mExtrarepay.setText(1000 * 14 * (Float.parseFloat(interest_rates) / 100) + "元");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        mShouldrepay.setText("1000" + "元");
        mInfo.setText(BaseUtils.getTel() + " 在微小借成功借款1000元");


        redSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mLendmoney.setText(500+progress*5+"");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if(progress>50){
                    seekBar.setProgress(100);
                    mLendmoney.setText("1000" );
                    getZHFY();
                }

                if(progress<=50){
                    seekBar.setProgress(0);
                    mLendmoney.setText("500");
                    getZHFY();
                }
                mShouldrepay.setText("");

            }
        });

        yelloSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mLendnums.setText(7+progress+"");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(seekBar.getProgress()>3){
                    seekBar.setProgress(7);
                }else {
                    seekBar.setProgress(0);
                }
                getZHFY();
            }
        });

        new Thread() {
            @Override
            public void run() {
                while (isRunning) {
                    SystemClock.sleep(1000);
                    handlers.sendEmptyMessage(BASETTIME);
                }
            }
        }.start();

    }

    private Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == BASETTIME) {
                if (mInfo != null) {
                    mInfo.next();
                    number++;
                    mInfo.setText(BaseUtils.getTel() + "在微小借成功借款1000元");
                }
            }
        }
    };

    /**
     * 设置轮播
     */
    private void setBannerdata() {
        //设置为无限滑动
        mBgabanner.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        mBgabanner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, Object model, int position) {
                ((ImageView) itemView).setImageResource((int) model);
            }
        });
        mBgabanner.setData(Arrays.asList(R.drawable.ic_banner, R.drawable.ic_banner,
                R.drawable.ic_banner), null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onValueEvent(ValueEvent event) {
        mLendmoney.setText("1000");
        mLendnums.setText("14");
        mExtrarepay.setText(1000 * 14 * (Float.parseFloat(interest_rates) / 100) + "元");
        mShouldrepay.setText("1000" + "元");

    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected void DetoryViewAndThing() {

    }

    @OnClick({R.id.wallet_creatBtn, R.id.rel_lendinfo, R.id.img_borrowhelp})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wallet_creatBtn:
                if (walletCreatBtn.getText().toString().equals("立即申请") || walletCreatBtn.getText().toString().equals("重新申请")) {
                    HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_MATERIAL, mContext,
                            new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)}), mContext, null, CommonValue.REQUEST_CODE3, this);
                    return;
                } else if (walletCreatBtn.getText().toString().equals("审核中")) {
                    showToast("审核中请勿重复申请");
                    return;
                } else if (walletCreatBtn.getText().toString().equals("立即提现")) {
                    Log.i(TAG, "onClick: " + bean.getCredit_user_usable());
                    if (bean.getCredit_user_usable() != 0) {
                        getMoneyDate();
                    } else {
                        showToast("您暂无可提余额");
                        return;
                    }
                } else if (walletCreatBtn.getText().toString().equals("再次申请")) {
                    openActivity(ApplyAgainActivity.class);
                    return;
                }
                break;
            case R.id.rel_lendinfo:
                openActivity(FindbankInfoActivity.class);
                break;

            case R.id.img_borrowhelp:
                setAmount();
                break;
        }
    }

    private void getMoneyDate() {
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.LOAN_USABLE, mContext,
                new String[]{"accessid"},
                new String[]{SPUtils.getAccessid(mContext)}), mContext, null, CommonValue.REQUEST_CODE2, this);
    }

    @Override
    public void onSuccess(String content, Info info, int requestCode) {
        switch (requestCode) {
            case CommonValue.REQUEST_CODE1:

                if (!TextUtils.isEmpty(content)) {
                    bean = JsonUtils.getInstance().jsonToObjectk(content, HomeWalletBean.class);
                    Log.e(TAG, "onSuccess: "+bean.toString());
                    if (bean != null) {
//                        Log.e("927", "首页auth_status状态: "+bean.getAuth_status());

                        String btnText = "";
                        if(bean.getAuth_status() == 2){
                            btnText =  "立即提现";//2 是审核通过，文案是立即提现
                        }else if(bean.getAuth_status() == 1 ){
                            btnText = "审核中";//1是审核中
                        }else if(bean.getAuth_status() == 3){
                            if(bean.getLoan_times()>1){
                                btnText = "再次申请";//3并且借款次数大于1 文案是再次申请
                            }else{
                                btnText = "重新申请";//3并且借款次数小于等于1 文案是重新申请
                            }
                        }else if(bean.getAuth_status() == 0 && bean.getLoan_times() > 1){
                            btnText = "再次申请";//0 并且借款次数大于1

                        }else{
                            btnText = "立即申请";//其他情况
                        }

                        walletCreatBtn.setText(""+btnText);
//                        walletCreatBtn.setText(
//                                bean.getAuth_status() == 2 ? "立即提现" :
//                                bean.getAuth_status() == 1 ? "审核中" :
//                                        bean.getAuth_status() == 3 ?  :"重新申请":
//                                                bean.getAuth_status() == 0 && bean.getLoan_times() > 1 ? "再次申请" : "立即申请");
                    }
                } else {
                    showToast("获取数据失败，请重新登陆");
                }
                break;
            case CommonValue.REQUEST_CODE2:
                if (!TextUtils.isEmpty(content)) {
                    Bundle bundle = new Bundle();
                    Log.e(TAG, "on主页接口的Success: "+content);
                    bundle.putSerializable("bean", JsonUtils.getInstance().jsonToObjectk(content, WithdrawalsBean.class));
                    openActivity(WithdrawalsActivity.class, bundle);
                } else {
                    showToast("系统忙，请重试");
                }
                break;
            case CommonValue.REQUEST_CODE3:
                if (!TextUtils.isEmpty(content)) {
                    Bundle applyBundle = new Bundle();
                    applyBundle.putInt("type", 1);
                    applyBundle.putSerializable("bean", JsonUtils.getInstance().jsonToObjectk(content, ApplyOneBean.class));
                    openActivity(ApplyOneActivity.class, applyBundle);
                } else {
                    showToast("系统忙，请重试");
                }
                break;

            case CommonValue.REQUEST_CODE4:

//                Log.e(TAG, "onSuccess: "+content);
                if (!TextUtils.isEmpty(content)) {
                    WalletFragmentMoeyBean moneyBean = JsonUtils.getInstance().jsonToObjectk(content, WalletFragmentMoeyBean.class);
                    if (moneyBean != null) {

                        //到期应还金额
                        mShouldrepay.setText("" + moneyBean.getLoan_amount());
                        //还TM要前端计算费率
                        //先把费率初始化了
                        interest_rates = moneyBean.getInterest_rate();
//                        Log.e(TAG, "利率String: " + interest_rates);

                        //开始计算综合费用《计算公式是：服务费+借款金额*借款天数*利率》
                        String service_amount_string = moneyBean.getService_amount();//服务费用
//                        Log.e(TAG, "服务费String: " + service_amount_string);


                        String loan_amount_string = moneyBean.getLoan_amount();
//                        Log.e(TAG, "借款金额String: " + loan_amount_string);


                        float min_days = 7+yelloSeekBar.getProgress();
//                        Log.e(TAG, "借款天数String: " + min_days);

                        /*--------------------------------------------------------*/

                        BigDecimal interest_rates_big = new BigDecimal(interest_rates);
                        Log.e(TAG, "利率BigDecimal: " + interest_rates_big);

                        BigDecimal service_amount_big = new BigDecimal(service_amount_string);
//                        Log.e(TAG, "服务费BigDecimal: " + service_amount_big);

                        BigDecimal loan_amount_big = new BigDecimal(loan_amount_string);
//                        Log.e(TAG, "借款金额BigDecimal: " + loan_amount_big);


                        BigDecimal min_days_big = new BigDecimal(min_days);
//                        Log.e(TAG, "借款天数BigDecimal: " + min_days_big);

                        //先进行计算利息《金额*天数*利率》
                        double v = loan_amount_big
                                .multiply(min_days_big)
                                .multiply(interest_rates_big)
                                .add(service_amount_big)
                                .doubleValue();//综合费用

                        mExtrarepay.setText("" + v);


                    }
                } else {
                    showToast("系统忙，请重试");
                }

                break;
        }
    }

    @Override
    public void onCacheSuccess(String content, Info info, int requestCode) {

    }

    @Override
    public void onError(Info info, int requestCode) {
        showToast(info.getMsg());
    }

    private void setAmount() {
        mDialog = new Dialog(mContext, R.style.dialogstyle);
        View view_cate = LayoutInflater.from(mContext).inflate(R.layout.dialog_amounttype, null);
        TextView txt = (TextView) view_cate.findViewById(R.id.txt_inteal);
        Log.e(TAG, "interest_rates: "+interest_rates);
        BigDecimal interest_rates_big = new BigDecimal(interest_rates);
        Log.e(TAG, "利率BigDecimal: " + interest_rates_big);
        txt.setText("服务费+借款金额*借款天数*" + interest_rates_big + "");
        mDialog.setContentView(view_cate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        //获得窗体的属性
        mDialog.setCancelable(true);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
        EventBus.getDefault().unregister(this);
    }
}
